package com.wang.experiment.experiment3.booksystem;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;

/**
 * @author wr
 * @date 2021/10/26 20:35
 */
public class SearchBookDialog extends JDialog {
    private final BookSystem bookSystem;
    private final BookManager manager;

    public SearchBookDialog(BookSystem bookSystem, BookManager manager) {
        super(bookSystem, "查询书籍", true);
        this.bookSystem = bookSystem;
        this.manager = manager;
        init();
    }

    private void init() {
        Rectangle parentBounds = getParent().getBounds();
        setBounds(parentBounds.x + parentBounds.width / 4,
                parentBounds.y + parentBounds.height / 4,
                parentBounds.width / 2,
                parentBounds.height / 2);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel mainPanel = new JPanel(new GridLayout(2,1,5,5));

        //init input
        JPanel keywordPanel = new JPanel(new FlowLayout());
        JLabel keyword = new JLabel("关键字:");
        JTextField keywordInput = new JTextField(16);
        keywordPanel.add(keyword);
        keywordPanel.add(keywordInput);
        mainPanel.add(keywordPanel);

        //btn init
        ButtonGroup buttonGroup = new ButtonGroup();
        JPanel radioButtonPanel = new JPanel(new FlowLayout());
        radioButtonPanel.setBorder(new TitledBorder("类型"));
        JRadioButton bookName = new JRadioButton("书籍名称", true);
        JRadioButton bookId = new JRadioButton("书籍id", false);
        buttonGroup.add(bookName);
        buttonGroup.add(bookId);
        radioButtonPanel.add(bookName);
        radioButtonPanel.add(bookId);
        mainPanel.add(radioButtonPanel);

        add(mainPanel,BorderLayout.CENTER);

        JPanel searchPanel = new JPanel(new FlowLayout());
        JButton search = new JButton("搜索");
        search.addActionListener(e -> {
            if(keywordInput.getText().isEmpty()){
                JOptionPane.showMessageDialog(this, "未填写关键字", "警告", JOptionPane.WARNING_MESSAGE);
            }else {
                if(bookName.getModel().equals(buttonGroup.getSelection())){
                    bookSystem.showBookData(manager.getBooksByName(keywordInput.getText()));
                }else {
                    bookSystem.showBookData(manager.getBookById(keywordInput.getText()));
                }
            }
        });
        searchPanel.add(search);
        add(searchPanel, BorderLayout.SOUTH);


        setVisible(true);
    }
}
